package com.googlecode.imule.redundant;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**
 * The ListenerThread monitors a socket for incoming data and prints whatever
 * it receives.
 * 
 * @author Graeme Stevenson
 * @author Graham Williamson
 */
public class CommThread extends Thread {
	/** Indicates if this thread should shut down */
	private boolean shutdown;

	/** The socket to be monitored by this listener. */
	private DatagramSocket socket;

	/** The packet to be filled with received data. */
	private DatagramPacket packet;
	
		
	/**
	 * Creates a new listener thread to monitor a socket.
	 * @param socket the socket to be monitored by this listener.
	 * @param packet the packet to be filled with received data.
	 */
	public CommThread(DatagramSocket socket, DatagramPacket packet) {
		this.shutdown = false;
		this.socket = socket;
		this.packet = packet;
	}
	
	/**
	 * The run method monitors the socket for incoming data, printing whatever
	 * it gets...
	 */
	public void run() {
		while (!shouldShutdown()) {
			try {
				socket.receive(packet);
				//System.out.println(new String(packet.getData(), 0, packet.getLength()));
			} catch (Exception e) {
				e.printStackTrace();
				break; // terminate thread
			}
		}
	}

	/**
	 * Check if we should shutdown the listener thread.
	 * @return true if we should shutdown; false otherwise.
	 */
	public synchronized boolean shouldShutdown() {
		return shutdown;
	}
	
	/**
	 * Notify this listener thread that it should shutdown.
	 */
	public synchronized void shutdown() {
		shutdown = true;
	}

}